# coding=utf-8
"""
Copyright 2019-2020 Fang Jin Biao

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

# @Time    : 2020/8/15 18:28
# @Author  : Fang Jin Biao
# @Email   : 215466914@qq.com
# @File    : emai_api.py
# @Project : SnowAdminWeb

from flask import Blueprint, request, jsonify, session, send_file, send_from_directory, Response, g

from flask_restful import Api, Resource, marshal_with
from flask_restful.reqparse import RequestParser
import os
import time
from webapp import db
from webapp.models import Thesis
from webapp.config.api_utils import oper_log
from webapp.dto_mapper import tool_email_config_fields
from webapp.schema import ToolEmailConfigSchema
from webapp.service.sys_tools_service import ToolEmailConfigService
from io import SEEK_END
from datetime import datetime
import json

thesis_app = Blueprint('thesis', __name__, url_prefix='/api/thesis')
thesis_api = Api(thesis_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=False)
parser.add_argument('fromUser', location='json', type=str, trim=True, required=True)
parser.add_argument('host', location='json', type=str, trim=True, required=True)
parser.add_argument('pass', location='json', type=str, trim=True, required=True)
parser.add_argument('port', location='json', type=str, trim=True, required=True)
parser.add_argument('user', location='json', type=str, trim=True, required=True)
from webapp.config import ServerConfig
from webapp.dto_mapper import thesis_page_fields
import io


@thesis_api.resource('/upload')
class thesis_upload(Resource):
    def post(self):
        current_user = json.loads(g.get("user"))
        basepath = os.path.dirname(__file__)
        file = request.files.get('file')
        fsize = file.seek(0, SEEK_END)
        if fsize > 50 * 1024 * 1024:
            return jsonify({'code': 500, 'error': '文件不能超过50MB!'})
        file.seek(0, os.SEEK_SET)
        filenametotal = file.filename  # 获取文件名信息
        # 获取到文件后缀名
        # print(file_name)
        file_name_arr = filenametotal.split('.')
        filename = file_name_arr[0]
        ext = file_name_arr[1]
        # 生成新的名字
        time_name = int(time.time())
        new_file_name = str(time_name)
        staticfile = "/static/upload_thesis/" + new_file_name + "." + ext
        save_path = os.path.join(basepath, "../../" + staticfile)  # 拼接文件上传物理路径
        file.save(save_path)  # 保存文件
        thesis = Thesis()
        thesis.filename = filenametotal
        thesis.url = staticfile
        thesis.user_id = current_user["id"]
        thesis.filesize = fsize
        thesis.createdate = datetime.now()
        db.session.add(thesis)
        db.session.flush()
        thesisId = thesis.id
        db.session.commit()
        return jsonify({'code': 200, 'imgUrl': staticfile, 'id': thesisId})


@thesis_api.resource('/uploadOnlyUser')
class thesis_upload_onlyUser(Resource):
    @marshal_with(thesis_page_fields)
    def get(self):
        params = request.args
        data = json.loads(g.get("user"))
        user_id = data["id"]
        page= params.get('page',1)
        size =params.get('size',9999)
        create_times = params.get('createTime')
        query = []
        sort_params = [Thesis.createdate.desc()]
        if user_id:
            query.append(Thesis.user_id == user_id)
        if create_times and len(create_times) >= 2:
            query.append((Thesis.createdate.between(create_times[0], create_times[1])))
        return Thesis.query.filter(*query).order_by(*sort_params).paginate(int(page), per_page=int(size),
                                                                                     error_out=False)

    def post(self):
        data = request.get_json()
        current_user = json.loads(g.get("user"))
        thesis = Thesis()
        thesis.filename = data["filename"]
        thesis.url = data["url"]
        thesis.user_id = current_user["id"]
        thesis.filesize = data["size"]
        thesis.createdate = datetime.now()
        db.session.add(thesis)
        db.session.flush()
        thesisId = thesis.id
        db.session.commit()
        return jsonify({'code': 200, 'imgUrl': data["url"], 'id': thesisId})

    def put(self):
        data = request.get_json()
        old_data = Thesis.query.filter(Thesis.id == data.get("id")).one()
        old_data.coversation_id = data.get("conversation_id")
        db.session.commit()

    def delete(self):
        ids = request.get_json()
        old_list = Thesis.query.filter(Thesis.id.in_(ids)).all()
        for d in old_list:
            file_path = os.path.join(ServerConfig.savepath, "./"+d.url)
            if os.path.isfile(file_path):
                os.remove(file_path)
            db.session.delete(d)
        db.session.commit()

@thesis_api.resource('/select')
class thesisselect(Resource):
    def get(self):
        current_user = json.loads(g.get("user"))
        list = Thesis.query.filter(Thesis.user_id == current_user["id"]).order_by(Thesis.createdate.desc()).all()
        return jsonify({'msg': '操作成功', 'code': 200, "data": [res.to_json() for res in list]})


@thesis_api.resource('/selectbyid')
class thesisselectbyid(Resource):
    def get(self):
        id = request.args.get('id')
        list = Thesis.query.filter(Thesis.id == id).first()
        return jsonify({'msg': '操作成功', 'code': 200, "data": list.to_json()})


@thesis_api.resource('/download')
class download_file(Resource):
    def get(self):
        path = request.args.get('path')
        pathname = os.path.join(ServerConfig.UPLOADED_FOLDER, path)

        def send_chunk():  # 流式读取
            with open(pathname, 'rb') as target_file:
                while True:
                    chunk = target_file.read(2 * 1024 * 1024)  # 每次读取20M
                    if not chunk:
                        break
                    yield chunk

        return Response(send_chunk(), content_type='application/octet-stream')


@thesis_api.resource('/downloadSendFile')
class downloadSendFile(Resource):
    def get(self):
        path = request.args.get('path')
        file_path = os.path.join(ServerConfig.UPLOADED_FOLDER, path)
        if not os.path.exists(file_path):
            return "File not found", 404
        return send_file(file_path, as_attachment=True)
